<template>
  <view class="add-work-container">
    <!-- 页头 -->
    <view class="header">
      <view class="header-content">
        <view class="back-btn" @click="goBack">
          <image
            class="back-icon"
            src="/static/icons/candidate/pre_page.png"
          ></image>
        </view>
        <text class="header-title">添加工作经历</text>
        <view class="save-btn" @click="saveWorkExperience">
          <text class="save-text">保存</text>
        </view>
      </view>
    </view>

    <!-- 表单内容 -->
    <view class="form-content">
      <view class="card-box">
        <!-- 公司名称 -->
        <view class="block-name">
          <text class="field-lable-words">公司名称</text>
          <view class="field-wrapper" @click="goToCompanyInput">
            <text
              class="company-input"
              :class="{ placeholder: !formData.companyName }"
            >
              {{ formData.companyName || "请输入" }}
            </text>
            <image
              src="/static/icons/right-arrow-gray.png"
              class="right-arrow"
            ></image>
          </view>
        </view>

        <view class="line-wrapper"><view class="line"></view></view>

        <!-- 所在行业 -->
        <view class="block-name">
          <text class="field-lable-words">所在行业</text>
          <view class="field-wrapper" @click="goToIndustrySelect">
            <text
              class="company-input"
              :class="{ placeholder: !formData.industry }"
            >
              {{ formData.industry || "请选择" }}
            </text>
            <image
              src="/static/icons/right-arrow-gray.png"
              class="right-arrow"
            ></image>
          </view>
        </view>

        <view class="line-wrapper"><view class="line"></view></view>

        <!-- 在职时间 -->
        <view class="block-name">
          <text class="field-lable-words">在职时间</text>
          <view class="job-day-wrapper">
            <picker
              mode="multiSelector"
              :range="beginDateRange"
              :value="beginDateIndex"
              @change="onStartDateChange"
              :class="!formData.beginDate ? 'picker' : 'picker-words'"
            >
              <view class="field-words">{{
                formData.beginDate || "开始时间"
              }}</view>
            </picker>
            <text class="day-split">—</text>
            <picker
              mode="multiSelector"
              :range="endDateRange"
              :value="endDateIndex"
              @change="onEndDateChange"
              :class="!formData.endDate ? 'picker' : 'picker-words'"
            >
              <view class="field-words">{{
                formData.endDate || "结束时间"
              }}</view>
            </picker>
          </view>
        </view>

        <view class="line-wrapper"><view class="line"></view></view>

        <!-- 职位名称 -->
        <view class="block-name">
          <text class="field-lable-words">职位名称</text>
          <view class="field-wrapper" @click="goToPositionSelect">
            <text
              class="company-input"
              :class="{ placeholder: !formData.position }"
            >
              {{ formData.position || "请选择" }}
            </text>
            <image
              src="/static/icons/right-arrow-gray.png"
              class="right-arrow"
            ></image>
          </view>
        </view>

        <view class="line-wrapper"><view class="line"></view></view>

        <!-- 工作内容 -->
        <view class="block-name">
          <text class="field-lable-words">工作内容</text>
          <view class="field-wrapper" @click="goToContentInput">
            <text
              class="company-input"
              :class="{ placeholder: !formData.contentHtml }"
            >
              {{ getDisplayContent(formData.contentHtml) || "请输入" }}
            </text>
            <image
              src="/static/icons/right-arrow-gray.png"
              class="right-arrow"
            ></image>
          </view>
        </view>

        <view class="line-wrapper"><view class="line"></view></view>

        <!-- 所属部门 -->
        <view class="block-name">
          <text class="field-lable-words">所属部门</text>
          <view class="field-wrapper" @click="goToDepartmentInput">
            <text
              class="company-input"
              :class="{ placeholder: !formData.department }"
            >
              {{ formData.department || "选填 请输入" }}
            </text>
            <image
              src="/static/icons/right-arrow-gray.png"
              class="right-arrow"
            ></image>
          </view>
        </view>
      </view>
    </view>

    <!-- 删除按钮（仅在编辑模式下显示） -->
    <view v-if="isEdit" class="delete-section">
      <view class="delete-btn" @click="showDeleteConfirm">
        <text class="delete-text">删除工作经历</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import {
  submitWorkExperience,
  deleteWorkExperience,
  getWorkExperienceDetail,
} from "../../../api/resume.js";

// 表单数据
const formData = ref({
  id: "", // 工作经历ID（编辑时需要）
  companyName: "",
  industry: "",
  beginDate: "",
  endDate: "",
  position: "",
  content: "",
  department: "",
});

// 简历ID
const resumeId = ref("");
// 是否为编辑模式
const isEdit = ref(false);
// 工作经历ID
const workExpId = ref("");

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 获取工作内容显示文本（最多100字）
const getDisplayContent = (content) => {
  if (!content) return "";

  // 移除HTML标签获取纯文本
  const plainText = content.replace(/<[^>]*>/g, "");

  // 如果超过100字，截取前100字并添加省略号
  if (plainText.length > 100) {
    return plainText.substring(0, 100) + "...";
  }

  return plainText;
};

// 保存工作经历
const saveWorkExperience = () => {
  console.log("保存工作经历:", formData.value);

  // 表单验证
  if (!formData.value.companyName) {
    uni.showToast({
      title: "请输入公司名称",
      icon: "none",
    });
    return;
  }

  if (!formData.value.industry) {
    uni.showToast({
      title: "请选择所在行业",
      icon: "none",
    });
    return;
  }

  if (!formData.value.beginDate) {
    uni.showToast({
      title: "请选择开始时间",
      icon: "none",
    });
    return;
  }

  if (!formData.value.endDate) {
    uni.showToast({
      title: "请选择结束时间",
      icon: "none",
    });
    return;
  }

  if (!formData.value.position) {
    uni.showToast({
      title: "请输入职位名称",
      icon: "none",
    });
    return;
  }

  if (!formData.value.department) {
    uni.showToast({
      title: "请输入所属部门",
      icon: "none",
    });
    return;
  }

  // 构建提交数据
  const submitData = {
    resumeId: resumeId.value,
    companyName: formData.value.companyName,
    industry: formData.value.industry,
    beginDate: formData.value.beginDate,
    endDate: formData.value.endDate,
    position: formData.value.position,
    department: formData.value.department,
    content: formData.value.content
      ? formData.value.content.replace(/<[^>]*>/g, "")
      : "",
    contentHtml: formData.value.content || "",
  };

  // 如果是编辑模式，添加ID
  if (isEdit.value && workExpId.value) {
    submitData.id = workExpId.value;
  }

  console.log("提交数据:", submitData);

  // 调用接口保存
  submitWorkExperience(submitData)
    .then((response) => {
      console.log("保存成功:", response);
      uni.showToast({
        title: isEdit.value ? "更新成功" : "保存成功",
        icon: "success",
      });

      // 延迟跳转回简历页面，确保用户看到成功提示
      setTimeout(() => {
        uni.reLaunch({
          url: "/pages/candidate/resume/resume",
        });
      }, 1500);
    })
    .catch((error) => {
      console.log("保存失败:", error);
      uni.showToast({
        title: "保存失败，请重试",
        icon: "none",
      });
    });
};

// 显示删除确认对话框
const showDeleteConfirm = () => {
  uni.showModal({
    title: "确认删除",
    content: "确定要删除这条工作经历吗？删除后无法恢复。",
    confirmText: "删除",
    confirmColor: "#ff4757",
    cancelText: "取消",
    success: (res) => {
      if (res.confirm) {
        deleteWorkExp();
      }
    },
  });
};

// 删除工作经历
const deleteWorkExp = () => {
  if (!workExpId.value) {
    uni.showToast({
      title: "无法删除，缺少工作经历ID",
      icon: "none",
    });
    return;
  }

  deleteWorkExperience(workExpId.value)
    .then((response) => {
      console.log("删除成功:", response);
      uni.showToast({
        title: "删除成功",
        icon: "success",
      });

      // 延迟跳转回简历页面
      setTimeout(() => {
        uni.reLaunch({
          url: "/pages/candidate/resume/resume",
        });
      }, 1500);
    })
    .catch((error) => {
      console.log("删除失败:", error);
      uni.showToast({
        title: "删除失败，请重试",
        icon: "none",
      });
    });
};

// 跳转到公司名称输入页面
const goToCompanyInput = () => {
  uni.navigateTo({
    url: `/pages/candidate/resume/commonInput?type=companyName&value=${encodeURIComponent(
      formData.value.companyName || ""
    )}`,
  });
};

// 跳转到行业选择页面
const goToIndustrySelect = () => {
  uni.navigateTo({
    url: `/pages/candidate/resume/industrySelect?value=${encodeURIComponent(
      formData.value.industry || ""
    )}`,
  });
};

// 跳转到职位选择页面
const goToPositionSelect = () => {
  uni.navigateTo({
    url: `/pages/candidate/resume/commonInput?type=position&value=${encodeURIComponent(
      formData.value.position || ""
    )}`,
  });
};

// 跳转到工作内容输入页面
const goToContentInput = () => {
  uni.navigateTo({
    url: `/pages/candidate/resume/richTextEditor?type=workContent&value=${encodeURIComponent(
      formData.value.contentHtml || formData.value.content || ""
    )}`,
  });
};

// 跳转到部门输入页面
const goToDepartmentInput = () => {
  uni.navigateTo({
    url: `/pages/candidate/resume/commonInput?type=department&value=${encodeURIComponent(
      formData.value.department || ""
    )}`,
  });
};

// 生成开始时间选择器数据
const generateBeginDateRange = () => {
  const currentYear = new Date().getFullYear();
  const years = [];
  const months = [];

  // 生成年份：从今年到1990年（倒序）
  for (let year = currentYear; year >= 1990; year--) {
    years.push(year + "年");
  }

  // 添加"1990之前"选项到最后
  years.push("1990之前");

  // 生成月份：1月到12月
  for (let month = 1; month <= 12; month++) {
    months.push(month + "月");
  }

  return [years, months];
};

// 生成结束时间选择器数据
const generateEndDateRange = () => {
  const currentYear = new Date().getFullYear();
  const years = [];
  const months = [];

  // 添加"至今"选项到最前面
  years.push("至今");

  // 生成年份：从今年到1990年（倒序）
  for (let year = currentYear; year >= 1990; year--) {
    years.push(year + "年");
  }

  // 生成月份：1月到12月
  for (let month = 1; month <= 12; month++) {
    months.push(month + "月");
  }

  return [years, months];
};

const beginDateRange = generateBeginDateRange();
const endDateRange = generateEndDateRange();

// 当前选中的索引
const beginDateIndex = ref([0, 0]); // [年份索引, 月份索引]
const endDateIndex = ref([0, 0]);
const endDateType = ref("date"); // 'date' 或 'present'

// 开始时间选择
const onStartDateChange = (e) => {
  const [yearIndex, monthIndex] = e.detail.value;
  beginDateIndex.value = [yearIndex, monthIndex];

  const yearText = beginDateRange[0][yearIndex];

  if (yearText === "1990之前") {
    // 1990之前不需要月份
    formData.value.beginDate = "1990之前";
  } else {
    // 1990年及以后需要月份
    const year = yearText.replace("年", "");
    const month = beginDateRange[1][monthIndex].replace("月", "");
    formData.value.beginDate = `${year}-${month.padStart(2, "0")}`;
  }

  // 验证开始时间是否在结束时间之前
  validateStartDate();
};

// 结束时间选择
const onEndDateChange = (e) => {
  const [yearIndex, monthIndex] = e.detail.value;
  endDateIndex.value = [yearIndex, monthIndex];

  const yearText = endDateRange[0][yearIndex];

  if (yearText === "至今") {
    // 选择"至今"时，不需要月份
    formData.value.endDate = "至今";
  } else {
    // 选择具体年月
    const year = yearText.replace("年", "");
    const month = endDateRange[1][monthIndex].replace("月", "");
    formData.value.endDate = `${year}-${month.padStart(2, "0")}`;
  }

  // 验证结束时间是否在开始时间之后
  validateEndDate();
};

// 验证开始时间是否在结束时间之前
const validateStartDate = () => {
  if (!formData.value.beginDate || !formData.value.endDate) {
    return true;
  }

  // 如果开始时间是"1990之前"，则总是有效
  if (formData.value.beginDate === "1990之前") {
    return true;
  }

  // 如果结束时间是"至今"，则总是有效
  if (formData.value.endDate === "至今") {
    return true;
  }

  // 如果开始时间是"1990之前"且结束时间是"至今"，则总是有效
  if (
    formData.value.beginDate === "1990之前" &&
    formData.value.endDate === "至今"
  ) {
    return true;
  }

  // 比较具体年月
  if (
    formData.value.beginDate &&
    formData.value.endDate &&
    formData.value.beginDate !== "1990之前" &&
    formData.value.endDate !== "至今"
  ) {
    const beginDate = new Date(formData.value.beginDate + "-01");
    const endDate = new Date(formData.value.endDate + "-01");

    if (beginDate > endDate) {
      uni.showToast({
        title: "开始时间不能晚于结束时间",
        icon: "none",
      });
      // 重置开始时间
      formData.value.beginDate = "";
      beginDateIndex.value = [0, 0];
      return false;
    }
  }

  return true;
};

// 验证结束时间是否在开始时间之后
const validateEndDate = () => {
  if (!formData.value.beginDate || !formData.value.endDate) {
    return true;
  }

  // 如果开始时间是"1990之前"，则总是有效
  if (formData.value.beginDate === "1990之前") {
    return true;
  }

  // 如果结束时间是"至今"，则总是有效
  if (formData.value.endDate === "至今") {
    return true;
  }

  // 如果开始时间是"1990之前"且结束时间是"至今"，则总是有效
  if (
    formData.value.beginDate === "1990之前" &&
    formData.value.endDate === "至今"
  ) {
    return true;
  }

  // 比较具体年月
  if (
    formData.value.beginDate &&
    formData.value.endDate &&
    formData.value.beginDate !== "1990之前" &&
    formData.value.endDate !== "至今"
  ) {
    const beginDate = new Date(formData.value.beginDate + "-01");
    const endDate = new Date(formData.value.endDate + "-01");

    if (endDate < beginDate) {
      uni.showToast({
        title: "结束时间不能早于开始时间",
        icon: "none",
      });
      // 重置结束时间
      formData.value.endDate = "";
      endDateIndex.value = [0, 0];
      return false;
    }
  }

  return true;
};

// 更新字段值（从子页面返回时调用）
const updateFieldValue = (field, value) => {
  if (formData.value.hasOwnProperty(field)) {
    formData.value[field] = value;
  }
};

// 暴露方法给子页面调用
defineExpose({
  updateFieldValue,
});

// 页面加载时设置事件监听器
onMounted(() => {
  // 获取页面参数中的简历ID
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options || {};

  if (options.resumeId) {
    resumeId.value = decodeURIComponent(options.resumeId);
    console.log("获取到简历ID:", resumeId.value);
  }

  // 获取工作经历ID（编辑模式）
  if (options.id) {
    isEdit.value = true;
    workExpId.value = decodeURIComponent(options.id);
    console.log("获取到工作经历ID:", workExpId.value);

    // 调用API获取工作经历详情
    uni.showLoading({
      title: "加载中",
    });
    getWorkExperienceDetail(workExpId.value)
      .then((response) => {
        uni.hideLoading();
        if (response) {
          formData.value = response;

          // 安全地解析日期字符串
          try {
            // 处理开始时间
            if (
              formData.value.beginDate &&
              formData.value.beginDate !== "1990之前"
            ) {
              // 检查日期格式是否为 YYYY-MM 或 YYYY-MM-DD
              if (formData.value.beginDate.includes("-")) {
                const [year, month] = formData.value.beginDate.split("-");
                if (year && month && !isNaN(year) && !isNaN(month)) {
                  // 如果是 YYYY-MM 格式，添加日期部分
                  const dateStr =
                    formData.value.beginDate.length === 7
                      ? formData.value.beginDate + "-01"
                      : formData.value.beginDate;
                  const beginDate = new Date(dateStr);
                  if (!isNaN(beginDate.getTime())) {
                    formData.value.beginDate = beginDate
                      .toISOString()
                      .slice(0, 10);
                  }
                }
              }
            }

            // 处理结束时间
            if (formData.value.endDate && formData.value.endDate !== "至今") {
              // 检查日期格式是否为 YYYY-MM 或 YYYY-MM-DD
              if (formData.value.endDate.includes("-")) {
                const [year, month] = formData.value.endDate.split("-");
                if (year && month && !isNaN(year) && !isNaN(month)) {
                  // 如果是 YYYY-MM 格式，添加日期部分
                  const dateStr =
                    formData.value.endDate.length === 7
                      ? formData.value.endDate + "-01"
                      : formData.value.endDate;
                  const endDate = new Date(dateStr);
                  if (!isNaN(endDate.getTime())) {
                    formData.value.endDate = endDate.toISOString().slice(0, 10);
                  }
                }
              }
            }
          } catch (dateError) {
            console.warn("日期解析失败，使用原始值:", dateError);
          }

          // 设置开始时间选择器
          try {
            if (
              formData.value.beginDate &&
              formData.value.beginDate !== "1990之前"
            ) {
              const [year, month] = formData.value.beginDate.split("-");
              if (year && month) {
                const beginYearIndex = beginDateRange[0].findIndex((item) =>
                  item.includes(year)
                );
                const beginMonthIndex = beginDateRange[1].findIndex((item) =>
                  item.includes(month)
                );
                if (beginYearIndex >= 0 && beginMonthIndex >= 0) {
                  beginDateIndex.value = [beginYearIndex, beginMonthIndex];
                }
              }
            }
          } catch (error) {
            console.warn("设置开始时间选择器失败:", error);
          }

          // 设置结束时间选择器
          try {
            if (formData.value.endDate && formData.value.endDate !== "至今") {
              const [year, month] = formData.value.endDate.split("-");
              if (year && month) {
                const endYearIndex = endDateRange[0].findIndex((item) =>
                  item.includes(year)
                );
                const endMonthIndex = endDateRange[1].findIndex((item) =>
                  item.includes(month)
                );
                if (endYearIndex >= 0 && endMonthIndex >= 0) {
                  endDateIndex.value = [endYearIndex, endMonthIndex];
                }
              }
            }
          } catch (error) {
            console.warn("设置结束时间选择器失败:", error);
          }

          // 判断结束时间是否为"至今"
          if (formData.value.endDate === "至今") {
            endDateType.value = "present";
          }
        } else {
          uni.hideLoading();
          uni.showToast({
            title: "加载工作经历失败",
            icon: "none",
          });
        }
      })
      .catch((error) => {
        uni.hideLoading();
        console.log("加载工作经历失败:", error);
        uni.showToast({
          title: "加载工作经历失败，请重试",
          icon: "none",
        });
      });
  }

  // 监听公司名称更新事件
  uni.$on("updateCompanyName", (value) => {
    formData.value.companyName = value;
  });

  // 监听行业更新事件
  uni.$on("updateIndustry", (value) => {
    formData.value.industry = value;
  });

  // 监听职位名称更新事件
  uni.$on("updatePosition", (value) => {
    formData.value.position = value;
  });

  // 监听富文本内容更新事件
  uni.$on("updateRichText", (data) => {
    if (data.type === "workContent") {
      formData.value.content = data.content;
      formData.value.contentHtml = data.content; // 同时更新contentHtml字段
    }
  });

  // 监听工作内容更新事件（兼容旧版本）
  uni.$on("updateContent", (value) => {
    formData.value.content = value;
    formData.value.contentHtml = value; // 同时更新contentHtml字段
  });

  // 监听所属部门更新事件
  uni.$on("updateDepartment", (value) => {
    formData.value.department = value;
  });
});

// 页面卸载时移除事件监听器
onUnmounted(() => {
  uni.$off("updateCompanyName");
  uni.$off("updateIndustry");
  uni.$off("updatePosition");
  uni.$off("updateRichText");
  uni.$off("updateContent");
  uni.$off("updateDepartment");
});
</script>

<style scoped lang="less">
.add-work-container {
  background-color: #fff;
  min-height: 100vh;
}

/* 页头样式 */
.header {
  background-color: #ffffff;
  border-bottom: 1px solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  height: 88rpx;
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 48rpx;
  height: 48rpx;
}

.header-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
    "Helvetica Neue", Arial, sans-serif;
}

.save-btn {
  min-width: 80rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 10rpx;
}

.save-text {
  font-size: 32rpx;
  color: #333;
  font-weight: 400;
}

/* 表单内容样式 */
.form-content {
  background-color: #ffffff;
  border-radius: 12rpx;
  overflow: hidden;
}

/* 卡片样式 */
.card-box {
  background-color: #ffffff;
  border-radius: 12rpx;
  overflow: hidden;
}

/* 字段块样式 */
.block-name {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  padding: 40rpx 30rpx;
  position: relative;
}

.field-lable-words {
  font-size: 28rpx;
  color: #a6a6a6;
  font-weight: 400;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
    "Helvetica Neue", Arial, sans-serif;
  margin-bottom: 20rpx;
}

.field-wrapper {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.company-input {
  font-size: 32rpx;
  color: #333;
  font-weight: 400;
  flex: 1;
  text-align: left;
  margin-right: 20rpx;
}

.placeholder {
  color: #999;
}

.right-arrow {
  width: 32rpx;
  height: 32rpx;
  opacity: 0.6;
  flex-shrink: 0;
}

/* 分割线样式 */
.line-wrapper {
  margin: 0 30rpx;
}

.line {
  height: 1px;
  background-color: #f0f0f0;
  width: 100%;
}

/* 时间选择器样式 */
.job-day-wrapper {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.picker {
  padding: 10rpx 20rpx;
  border-radius: 8rpx;
  flex: 1;
  max-width: 200rpx;
}

.picker-words {
  background-color: transparent;
  padding: 10rpx 20rpx;
  flex: 1;
  max-width: 200rpx;
}

.field-words {
  font-size: 32rpx;
  color: #a6a6a6;
  font-weight: 400;
  text-align: center;
}

.day-split {
  font-size: 32rpx;
  color: #333;
  font-weight: 400;
  margin: 0 30rpx;
  flex-shrink: 0;
}

/* 选填项提示样式 */
.optional-tip {
  padding: 20rpx 30rpx;
  background-color: #f8f9fa;
  display: flex;
  align-items: center;
  gap: 15rpx;
}

.info-icon {
  width: 32rpx;
  height: 32rpx;
  opacity: 0.6;
}

.tip-text {
  font-size: 28rpx;
  color: #666;
  font-weight: 400;
}

/* 删除按钮样式 */
.delete-section {
  padding: 20rpx 30rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
}

.delete-btn {
  background-color: #ff6f57;
  color: #fff;
  font-size: 32rpx;
  font-weight: 500;
  padding: 15rpx 30rpx;
  border-radius: 8rpx;
  text-align: center;
}

.delete-text {
  color: #fff;
}
</style>
